import React, { useState, useEffect } from "react";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { Button } from "@/components/ui/button";
import {
  ArrowLeft,
  Edit,
  GanttChartSquare,
  Info,
  MapPin,
  Zap,
  AlertCircle,
  Pilcrow,
  GitBranch,
  FolderOpen,
  Home,
  AlertTriangle,
  RefreshCw,
} from "lucide-react";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Card, CardContent } from "@/components/ui/card";
import { useToast } from "@/components/ui/use-toast";
import { ProjectAPI } from "@/api/project";
import { CrossingPointAPI } from "@/api/CrossingPoint";
import { ConstructionMethodTemplateAPI } from "@/api/ConstructionMethodTemplate";
import { TowerAPI } from "@/api/Towers";
import { ConstructionSchemeAPI } from "@/api/ConstructionScheme";
import { TensionSectionAPI } from "@/api/tensionSection";
import ProjectDetailContent from "../components/projects/ProjectDetailContent";
import ProjectCrossingPointsList from "../components/projects/ProjectCrossingPointsList";
import ProjectForm from "../components/projects/ProjectForm";
import ProjectTowersList from "../components/projects/ProjectTowersList";
import ProjectTensionSectionsList from "../components/projects/ProjectTensionSectionsList";
import TowerForm from "../components/towers/TowerForm";
import TensionSectionForm from "../components/projects/TensionSectionForm";

// 改进的重试逻辑
const retryApiCall = async (apiCall, maxRetries = 3, delay = 1000) => {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await apiCall();
    } catch (error) {
      console.log(`API调用失败，第 ${attempt} 次尝试:`, error.message);
      if (attempt === maxRetries) {
        throw error;
      }
      await new Promise((resolve) =>
        setTimeout(resolve, delay * Math.pow(2, attempt - 1))
      );
    }
  }
};

export default function ProjectDetail() {
  const [project, setProject] = useState(null);
  const [crossingPoints, setCrossingPoints] = useState([]);
  const [schemes, setSchemes] = useState([]);
  const [methodTemplates, setMethodTemplates] = useState([]);
  const [towers, setTowers] = useState([]);
  const [formTowers, setFormTowers] = useState([]);
  const [tensionSections, setTensionSections] = useState([]);
  const [activeTab, setActiveTab] = useState("basic");
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [workPlan, setWorkPlan] = useState(null);
  const [isOptimizing, setIsOptimizing] = useState(false);
  const [optimizationError, setOptimizationError] = useState(null);
  const [isEditing, setIsEditing] = useState(false);
  const [projectNotFound, setProjectNotFound] = useState(false);
  const [redirectCountdown, setRedirectCountdown] = useState(5);
  const [showTowerForm, setShowTowerForm] = useState(false);
  const [editingTower, setEditingTower] = useState(null);
  const [showTensionSectionForm, setShowTensionSectionForm] = useState(false);
  const [editingTensionSection, setEditingTensionSection] = useState(null);
  const [noProjectId, setNoProjectId] = useState(false);

  // New states for CrossingPoint
  const [editingCrossingPoint, setEditingCrossingPoint] = useState(null);
  const [showCrossingPointForm, setShowCrossingPointForm] = useState(false);

  const location = useLocation();
  const navigate = useNavigate();
  const { toast } = useToast();

  const handleAnalyzeScheme = (schemeId) => {
    if (schemeId) {
      navigate(`${createPageUrl("SchemeAnalysis")}?schemeId=${schemeId}`);
    } else {
      console.error("无效的方案ID: 无法分析空方案ID.");
    }
  };

  useEffect(() => {
    console.log("🔍 ========== ProjectDetail useEffect 开始 ==========");
    console.log("🔍 完整URL:", window.location.href);
    console.log("🔍 location对象:", location);
    console.log("🔍 location.pathname:", location.pathname);
    console.log("🔍 location.search:", location.search);
    console.log("🔍 location.hash:", location.hash);

    // 尝试多种方式获取参数
    const urlParams = new URLSearchParams(location.search);
    const projectIdFromSearch = urlParams.get("id");

    // 也尝试从window.location获取
    const windowUrlParams = new URLSearchParams(window.location.search);
    const projectIdFromWindow = windowUrlParams.get("id");

    console.log("🔍 从location.search获取的ID:", projectIdFromSearch);
    console.log("🔍 从window.location.search获取的ID:", projectIdFromWindow);
    console.log("🔍 URLSearchParams所有键:", Array.from(urlParams.keys()));
    console.log("🔍 URLSearchParams所有条目:", Array.from(urlParams.entries()));

    const projectId = projectIdFromSearch || projectIdFromWindow;

    console.log("🔍 最终使用的项目ID:", projectId);
    console.log("🔍 项目ID类型:", typeof projectId);
    console.log("🔍 项目ID长度:", projectId?.length);

    if (!projectId || projectId.trim() === "") {
      console.error("❌ URL中未提供项目ID或项目ID为空");
      console.error("❌ location.search 内容:", location.search);
      console.error("❌ window.location.search 内容:", window.location.search);
      console.error("❌ urlParams 内容:", Array.from(urlParams.entries()));

      setError("URL中未提供项目ID，请从项目列表选择一个项目查看详情");
      setNoProjectId(true);
      setIsLoading(false);

      toast({
        variant: "destructive",
        title: "访问错误",
        description: "未提供项目ID，5秒后将返回项目列表",
      });
      return;
    }

    console.log("✅ 项目ID有效，开始加载数据");
    console.log("🔍 ========== ProjectDetail useEffect 结束 ==========");
    loadData(projectId);
  }, [location.search, location.pathname, toast]);

  // 自动重定向倒计时（针对没有项目ID的情况）
  useEffect(() => {
    if (noProjectId && redirectCountdown > 0) {
      const timer = setTimeout(() => {
        setRedirectCountdown((prev) => prev - 1);
      }, 1000);
      return () => clearTimeout(timer);
    } else if (noProjectId && redirectCountdown === 0) {
      navigate(createPageUrl("Projects"));
    }
  }, [noProjectId, redirectCountdown, navigate]);

  // 自动重定向倒计时（针对项目不存在的情况）
  useEffect(() => {
    if (projectNotFound && redirectCountdown > 0) {
      const timer = setTimeout(() => {
        setRedirectCountdown((prev) => prev - 1);
      }, 1000);
      return () => clearTimeout(timer);
    } else if (projectNotFound && redirectCountdown === 0) {
      navigate(createPageUrl("Projects"));
    }
  }, [projectNotFound, redirectCountdown, navigate]);

  const loadData = async (projectId) => {
    setIsLoading(true);
    setError(null);
    setProjectNotFound(false);
    setNoProjectId(false);

    try {
      console.log("开始加载项目数据，项目ID:", projectId);

      // 第一步：先单独加载项目，确保项目存在
      let projectData = null;
      try {
        const projectRest = await retryApiCall(() => ProjectAPI.get(projectId));
        projectData = projectRest.data; // 从.data中提取项目数据
        console.log("✅ 项目数据加载成功:", projectData);
      } catch (projectError) {
        console.error("❌ 项目加载失败:", projectError);
        // 检查是否是404错误
        if (
          projectError.message &&
          (projectError.message.includes("not found") ||
            projectError.message.includes("404"))
        ) {
          setProjectNotFound(true);
          throw new Error(`项目不存在（ID: ${projectId}）`);
        }

        throw new Error("无法加载项目信息，请检查网络连接后重试。");
      }

      if (!projectData || !projectData.id) {
        throw new Error("项目数据格式无效");
      }

      setProject(projectData);

      // 第二步：并行加载其他数据
      const [
        crossingPointsResult,
        templatesResult,
        towersResult,
        tensionSectionsResult,
      ] = await Promise.allSettled([
        retryApiCall(() => CrossingPointAPI.filter(projectId)),
        retryApiCall(() => ConstructionMethodTemplateAPI.getList()),
        retryApiCall(() => TowerAPI.getList({ projectId: projectId })),
        // retryApiCall(() => TowerAPI.getList()),
        retryApiCall(() => TensionSectionAPI.getList({ projectId: projectId })),
      ]);

      const towersResponse = await TowerAPI.getList({ projectId: projectId });
      const latestFullTowers = Array.isArray(towersResponse.data)
        ? towersResponse.data
        : [];
      setFormTowers(latestFullTowers);

      // 处理跨越点结果：从.data提取
      const pointsData =
        crossingPointsResult.status === "fulfilled"
          ? crossingPointsResult.value.data || []
          : [];
      setCrossingPoints(Array.isArray(pointsData) ? pointsData : []);
      console.log("跨越点数据:", pointsData?.length || 0);

      // 处理模板结果：从.data提取
      const templatesData =
        templatesResult.status === "fulfilled"
          ? templatesResult.value.data || []
          : [];
      setMethodTemplates(Array.isArray(templatesData) ? templatesData : []);
      console.log("模板数据:", templatesData?.length || 0);

      // 处理杆塔结果：从.data提取
      const towersData =
        towersResult.status === "fulfilled"
          ? towersResult.value.data || []
          : [];
      setTowers(Array.isArray(towersData) ? towersData : []);
      console.log("杆塔数据:", towersData?.length || 0);

      // 处理勘查单结果：从.data提取
      const tensionSectionsData =
        tensionSectionsResult.status === "fulfilled"
          ? tensionSectionsResult.value.data || []
          : [];
      setTensionSections(
        Array.isArray(tensionSectionsData) ? tensionSectionsData : []
      );
      console.log("勘查单数据:", tensionSectionsData?.length || 0);

      // 第三步：如果有勘查单，加载施工方案
      if (tensionSectionsData && tensionSectionsData.length > 0) {
        try {
          const sectionIds = tensionSectionsData
            .map((ts) => ts.id)
            .filter((id) => id);
          if (sectionIds.length > 0) {
            const batchSize = 20;
            let schemeBatches = [];

            for (let i = 0; i < sectionIds.length; i += batchSize) {
              const batchIds = sectionIds.slice(i, i + batchSize);
              console.log(batchIds, "batchIdsbatchIds");

              try {
                const batchSchemesResult = await retryApiCall(() =>
                  ConstructionSchemeAPI.filterTensionSectionId(batchIds)
                );
                // 施工方案结果也从.data提取
                const batchSchemesData = batchSchemesResult.data || [];
                if (Array.isArray(batchSchemesData)) {
                  schemeBatches = [...schemeBatches, ...batchSchemesData];
                }
              } catch (batchError) {
                console.warn(
                  `施工方案批次加载失败 (${i}-${i + batchSize}):`,
                  batchError
                );
              }
            }
            setSchemes(schemeBatches);
            console.log("施工方案数据:", schemeBatches.length);
          } else {
            setSchemes([]);
          }
        } catch (error) {
          console.warn("加载施工方案失败:", error);
          setSchemes([]);
        }
      } else {
        setSchemes([]);
      }

      console.log("✅ 所有数据加载完成");
    } catch (error) {
      console.error("❌ 加载数据失败:", error);
      setError(error.message || "发生未知错误");
    } finally {
      setIsLoading(false);
    }
  };

  const handleSaveProject = async (projectData) => {
    if (!project?.id) {
      toast({
        variant: "destructive",
        title: "错误",
        description: "项目ID丢失，无法保存。",
      });
      return;
    }

    try {
      await ProjectAPI.update(project.id, projectData);
      toast({
        title: "更新成功",
        description: `项目 "${projectData.name}" 的信息已成功保存。`,
      });
      setIsEditing(false);
      await loadData(project.id);
    } catch (error) {
      console.error("更新项目失败:", error);
      toast({
        variant: "destructive",
        title: "更新失败",
        description: error.message || "无法保存项目信息，请稍后重试。",
      });
    }
  };

  // 保存跨越点
  const handleSaveCrossingPoint = async (pointData) => {
    try {
      if (editingCrossingPoint) {
        await CrossingPointAPI.update(editingCrossingPoint.id, pointData);
        toast({ title: "更新成功", description: "跨越点信息已更新" });
      } else {
        // 确保新项目的projectId
        const newPointData = { ...pointData, projectId: project.id };
        await CrossingPointAPI.create(newPointData);
        toast({ title: "创建成功", description: "跨越点已创建" });
      }
      setShowCrossingPointForm(false);
      setEditingCrossingPoint(null);
      await loadData(project.id);
    } catch (error) {
      console.error("保存跨越点失败:", error);
      toast({
        variant: "destructive",
        title: "保存失败",
        description: error.message || "无法保存跨越点信息",
      });
    }
  };

  // 保存杆塔
  const handleSaveTower = async (towerData) => {
    console.log(towerData, "towerDatatowerData");

    try {
      if (editingTower) {
        await TowerAPI.update(editingTower.id, towerData);
        toast({ title: "更新成功", description: "杆塔信息已更新" });
      } else {
        // 确保新项目的projectId
        const newTowerData = { ...towerData, projectId: project.id };
        await TowerAPI.create(newTowerData);
        toast({ title: "创建成功", description: "杆塔已创建" });
      }
      setShowTowerForm(false);
      setEditingTower(null);
      await loadData(project.id);
    } catch (error) {
      console.error("保存杆塔失败:", error);
      toast({
        variant: "destructive",
        title: "保存失败",
        description: error.message || "无法保存杆塔信息",
      });
    }
  };

  // 保存勘查单
  const handleSaveTensionSection = async (sectionData) => {
    console.log(sectionData, "sectionDatasectionData");
    console.log(8989898981111);

    try {
      if (editingTensionSection) {
        await TensionSectionAPI.update(editingTensionSection.id, sectionData);
        toast({ title: "更新成功", description: "勘查单信息已更新" });
      } else {
        // 确保新项目的projectId
        const newSectionData = { ...sectionData, projectId: project.id };

        await TensionSectionAPI.create(newSectionData);
        toast({ title: "创建成功", description: "勘查单已创建" });
      }
      setShowTensionSectionForm(false);
      setEditingTensionSection(null);
      await loadData(project.id);
    } catch (error) {
      console.error("保存勘查单失败:", error);
      toast({
        variant: "destructive",
        title: "保存失败",
        description: error.message || "无法保存勘查单信息",
      });
    }
  };

  const handleOptimizeProject = async () => {
    if (!project?.id) {
      setOptimizationError("项目信息不完整，无法进行优化");
      return;
    }

    setIsOptimizing(true);
    setOptimizationError(null);

    try {
    } catch (error) {
      console.error("优化失败:", error);
      setOptimizationError(error.message || "优化过程中发生错误，请稍后重试");
    } finally {
      setIsOptimizing(false);
    }
  };

  const renderTabContent = () => {
    switch (activeTab) {
      case "basic":
        return <ProjectDetailContent project={project} />;
      case "towers":
        return (
          <>
            {showTowerForm ? (
              <TowerForm
                tower={editingTower}
                projects={[project]}
                tensionSections={tensionSections}
                onSubmit={handleSaveTower}
                onCancel={() => {
                  setShowTowerForm(false);
                  setEditingTower(null);
                }}
              />
            ) : (
              <ProjectTowersList
                project={project}
                towers={towers}
                onEdit={(tower) => {
                  setEditingTower(tower);
                  setShowTowerForm(true);
                }}
                onDelete={async (towerId) => {
                  if (window.confirm("确定要删除此杆塔吗？")) {
                    try {
                      await TowerAPI.delete(towerId);
                      toast({ title: "删除成功", description: "杆塔已删除" });
                      loadData(project.id);
                    } catch (error) {
                      toast({
                        variant: "destructive",
                        title: "删除失败",
                        description: error.message,
                      });
                    }
                  }
                }}
                onAddNew={() => {
                  setEditingTower(null);
                  setShowTowerForm(true);
                }}
                // 新增：传递刷新数据的回调，调用父组件的loadData重新获取数据
                onRefresh={() => {
                  if (project?.id) {
                    loadData(project.id); // 关键：重新加载当前项目的所有数据（包括杆塔）
                  }
                }}
              />
            )}
          </>
        );
      case "crossings":
        return (
          <>
            {showCrossingPointForm ? null : (
              <>
                <ProjectCrossingPointsList
                  project={project}
                  crossingPoints={crossingPoints}
                  onRefreshCrossingPoints={() => {
                    if (project?.id) {
                      loadData(project.id);
                    }
                  }}
                  onEdit={(point) => {
                    setEditingCrossingPoint(point);
                    setShowCrossingPointForm(true);
                  }}
                  onDelete={async (pointId) => {
                    if (window.confirm("确定要删除此跨越点吗？")) {
                      try {
                        await CrossingPointAPI.delete(pointId);
                        toast({
                          title: "删除成功",
                          description: "跨越点已删除",
                        });
                        loadData(project.id);
                      } catch (error) {
                        toast({
                          variant: "destructive",
                          title: "删除失败",
                          description: error.message,
                        });
                      }
                    }
                  }}
                />
              </>
            )}
          </>
        );
      case "tensionSections":
        return (
          <>
            {showTensionSectionForm ? (
              <TensionSectionForm
                tensionSection={editingTensionSection}
                projects={[project]}
                projectId={project.id} // 传入项目ID
                projectName={project.projectName} // 传入项目名称，可选
                towers={formTowers}
                crossingPoints={crossingPoints}
                onSubmit={handleSaveTensionSection}
                onCancel={() => {
                  setShowTensionSectionForm(false);
                  setEditingTensionSection(null);
                }}
              />
            ) : (
              <ProjectTensionSectionsList
                project={project}
                tensionSections={tensionSections}
                towers={formTowers}
                crossingPoints={crossingPoints}
                onEdit={(section) => {
                  setEditingTensionSection(section);
                  setShowTensionSectionForm(true);
                }}
                onDelete={async (sectionId) => {
                  if (window.confirm("确定要删除此勘查单吗？")) {
                    try {
                      await TensionSectionAPI.delete(sectionId);
                      toast({ title: "删除成功", description: "勘查单已删除" });
                      loadData(project.id);
                    } catch (error) {
                      toast({
                        variant: "destructive",
                        title: "删除失败",
                        description: error.message,
                      });
                    }
                  }
                }}
                onAddNew={async () => {
                  setShowTensionSectionForm(false); // 先隐藏表单，避免数据混乱
                  // 显示表单（无论成功失败，都允许继续操作）
                  setEditingTensionSection(null);
                  setShowTensionSectionForm(true);
                }}
              />
            )}
          </>
        );
      default:
        return <ProjectDetailContent project={project} />;
    }
  };

  if (isLoading) {
    return (
      <div className="p-6 bg-gray-50 min-h-screen">
        <div className="max-w-7xl mx-auto">
          <div className="text-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
            <p className="text-lg font-medium text-gray-700">
              加载项目详情中...
            </p>
            <p className="text-sm text-gray-500 mt-2">
              正在获取项目信息和关联数据
            </p>
          </div>
        </div>
      </div>
    );
  }

  // 处理没有项目ID的情况
  if (noProjectId) {
    return (
      <div className="p-6 bg-gray-50 min-h-screen">
        <div className="max-w-3xl mx-auto">
          <Alert variant="destructive" className="mb-6">
            <AlertCircle className="h-5 w-5" />
            <AlertTitle className="text-lg font-semibold">访问错误</AlertTitle>
            <AlertDescription className="mt-2">
              URL中未提供项目ID，无法显示项目详情
            </AlertDescription>
          </Alert>

          <Card className="border-2 border-gray-200">
            <CardContent className="p-12 text-center">
              <div className="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-6">
                <FolderOpen className="w-10 h-10 text-gray-400" />
              </div>
              <h2 className="text-2xl font-bold text-gray-900 mb-3">
                无法访问项目详情
              </h2>
              <p className="text-gray-600 mb-2">
                当前URL中没有提供项目ID参数。
              </p>
              <p className="text-sm text-gray-500 mb-8">
                {redirectCountdown > 0 ? (
                  <>
                    将在
                    <span className="font-bold text-blue-600">
                      {redirectCountdown}
                    </span>
                    秒后自动返回项目列表...
                  </>
                ) : (
                  "正在跳转..."
                )}
              </p>

              <div className="flex flex-col sm:flex-row gap-3 justify-center">
                <Link to={createPageUrl("Projects")}>
                  <Button size="lg" className="w-full sm:w-auto">
                    <ArrowLeft className="w-4 h-4 mr-2" />
                    返回项目列表
                  </Button>
                </Link>
                <Link to={createPageUrl("Dashboard")}>
                  <Button
                    size="lg"
                    variant="outline"
                    className="w-full sm:w-auto"
                  >
                    <Home className="w-4 h-4 mr-2" />
                    返回首页
                  </Button>
                </Link>
              </div>

              <div className="mt-8 pt-8 border-t border-gray-200">
                <p className="text-sm text-gray-500 mb-4">
                  如何正确访问项目详情：
                </p>
                <ul className="text-sm text-gray-600 space-y-2 text-left max-w-md mx-auto">
                  <li className="flex items-start gap-2">
                    <AlertCircle className="w-4 h-4 text-gray-400 mt-0.5 flex-shrink-0" />
                    <span>从项目列表中点击"查看详情"按钮</span>
                  </li>
                  <li className="flex items-start gap-2">
                    <AlertCircle className="w-4 h-4 text-gray-400 mt-0.5 flex-shrink-0" />
                    <span>URL格式应为: /ProjectDetail?id=[项目ID]</span>
                  </li>
                </ul>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    );
  }

  if (projectNotFound || (error && error.includes("不存在"))) {
    return (
      <div className="p-6 bg-gray-50 min-h-screen">
        <div className="max-w-3xl mx-auto">
          <Alert variant="destructive" className="mb-6">
            <AlertCircle className="h-5 w-5" />
            <AlertTitle className="text-lg font-semibold">
              项目不存在
            </AlertTitle>
            <AlertDescription className="mt-2">
              {error || "您尝试访问的项目不存在或已被删除"}
            </AlertDescription>
          </Alert>

          <Card className="border-2 border-gray-200">
            <CardContent className="p-12 text-center">
              <div className="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-6">
                <FolderOpen className="w-10 h-10 text-gray-400" />
              </div>
              <h2 className="text-2xl font-bold text-gray-900 mb-3">
                找不到该项目
              </h2>
              <p className="text-gray-600 mb-2">
                您尝试访问的项目可能已被删除或不存在。
              </p>
              <p className="text-sm text-gray-500 mb-8">
                {redirectCountdown > 0 ? (
                  <>
                    将在{" "}
                    <span className="font-bold text-blue-600">
                      {redirectCountdown}
                    </span>{" "}
                    秒后自动返回项目列表...
                  </>
                ) : (
                  "正在跳转..."
                )}
              </p>

              <div className="flex flex-col sm:flex-row gap-3 justify-center">
                <Link to={createPageUrl("Projects")}>
                  <Button size="lg" className="w-full sm:w-auto">
                    <ArrowLeft className="w-4 h-4 mr-2" />
                    返回项目列表
                  </Button>
                </Link>
                <Link to={createPageUrl("Dashboard")}>
                  <Button
                    size="lg"
                    variant="outline"
                    className="w-full sm:w-auto"
                  >
                    <Home className="w-4 h-4 mr-2" />
                    返回首页
                  </Button>
                </Link>
              </div>

              <div className="mt-8 pt-8 border-t border-gray-200">
                <p className="text-sm text-gray-500 mb-4">可能的原因：</p>
                <ul className="text-sm text-gray-600 space-y-2 text-left max-w-md mx-auto">
                  <li className="flex items-start gap-2">
                    <AlertCircle className="w-4 h-4 text-gray-400 mt-0.5 flex-shrink-0" />
                    <span>项目已被其他用户删除</span>
                  </li>
                  <li className="flex items-start gap-2">
                    <AlertCircle className="w-4 h-4 text-gray-400 mt-0.5 flex-shrink-0" />
                    <span>链接地址错误或已过期</span>
                  </li>
                  <li className="flex items-start gap-2">
                    <AlertCircle className="w-4 h-4 text-gray-400 mt-0.5 flex-shrink-0" />
                    <span>您可能没有访问该项目的权限</span>
                  </li>
                </ul>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-6 bg-gray-50 min-h-screen">
        <div className="max-w-7xl mx-auto">
          <Alert variant="destructive" className="mb-6">
            <AlertCircle className="h-4 w-4" />
            <AlertTitle>加载失败</AlertTitle>
            <AlertDescription>{error}</AlertDescription>
          </Alert>

          <Card>
            <CardContent className="p-8 text-center">
              <AlertTriangle className="w-16 h-16 text-red-300 mx-auto mb-4" />
              <h3 className="text-lg font-semibold text-gray-900 mb-2">
                无法加载项目详情
              </h3>
              <p className="text-gray-600 mb-6">{error}</p>

              <div className="flex gap-3 justify-center">
                <Button
                  onClick={() => {
                    const urlParams = new URLSearchParams(location.search);
                    const projectId = urlParams.get("id");
                    if (projectId) loadData(projectId);
                  }}
                >
                  <RefreshCw className="w-4 h-4 mr-2" />
                  重试
                </Button>
                <Link to={createPageUrl("Projects")}>
                  <Button variant="outline">
                    <ArrowLeft className="w-4 h-4 mr-2" />
                    返回项目列表
                  </Button>
                </Link>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    );
  }

  if (!project) {
    return (
      <div className="p-6 bg-gray-50 min-h-screen">
        <div className="max-w-7xl mx-auto">
          <Alert variant="destructive" className="mb-6">
            <AlertCircle className="h-4 w-4" />
            <AlertTitle>项目数据无效</AlertTitle>
            <AlertDescription>无法加载项目数据</AlertDescription>
          </Alert>

          <Link to={createPageUrl("Projects")}>
            <Button>
              <ArrowLeft className="w-4 h-4 mr-2" />
              返回项目列表
            </Button>
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6 bg-gray-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="mb-6 flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4">
          <div className="flex-1">
            <Link
              to={createPageUrl("Projects")}
              className="text-sm text-blue-600 hover:underline flex items-center gap-1 mb-2"
            >
              <ArrowLeft className="w-4 h-4" />
              返回项目列表
            </Link>
            <h1 className="text-3xl font-bold text-gray-900 mb-2 flex items-center gap-3">
              <Zap className="w-8 h-8 text-blue-600 flex-shrink-0" />
              <span className="truncate">{project.projectName}</span>
            </h1>
            <p className="text-gray-600 text-sm">
              {project.voltageLevel} |{" "}
              {project.constructionUnit || "未指定施工单位"}
            </p>
          </div>
          <div className="flex gap-3 flex-shrink-0">
            <Button
              onClick={() => setIsEditing(true)}
              className="whitespace-nowrap"
            >
              <Edit className="w-4 h-4 mr-2" />
              编辑项目
            </Button>
          </div>
        </div>

        {isEditing ? (
          <ProjectForm
            project={project}
            onSubmit={handleSaveProject}
            onCancel={() => setIsEditing(false)}
          />
        ) : (
          <>
            {/* Tabs */}
            <div className="border-b border-gray-200 mb-6">
              <nav
                className="-mb-px flex space-x-8 overflow-x-auto"
                role="tablist"
              >
                {[
                  { id: "basic", label: "基本信息", icon: Info },
                  {
                    id: "towers",
                    label: `杆塔列表 (${towers.length})`,
                    icon: Pilcrow,
                  },
                  {
                    id: "crossings",
                    label: `跨越点列表 (${crossingPoints.length})`,
                    icon: MapPin,
                  },
                  {
                    id: "tensionSections",
                    label: `勘查单列表 (${tensionSections.length})`,
                    icon: GitBranch,
                  },
                ].map((tab) => (
                  <button
                    key={tab.id}
                    onClick={() => setActiveTab(tab.id)}
                    className={`py-2 px-1 border-b-2 font-medium text-sm transition-colors duration-200 whitespace-nowrap ${
                      activeTab === tab.id
                        ? "border-blue-500 text-blue-600"
                        : "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
                    }`}
                    role="tab"
                    aria-selected={activeTab === tab.id}
                  >
                    <tab.icon className="w-4 h-4 mr-2 inline" />
                    {tab.label}
                  </button>
                ))}
              </nav>
            </div>

            {/* Tab Content */}
            <div className="min-h-[400px]">{renderTabContent()}</div>
          </>
        )}
      </div>
    </div>
  );
}
